//
//  BROpenURL.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/10/18.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BROpenURL.h"

#define kInviteKey @"kBODInviteKey"

@implementation BROpenURL

+ (void)openMap:(CLLocationCoordinate2D)myLocation toLocation:(CLLocationCoordinate2D)toLocation {
    [[self class] openMap:myLocation toLocation:toLocation titleAddress:@""];
}

+ (void)openMap:(CLLocationCoordinate2D)myLocation toLocation:(CLLocationCoordinate2D)toLocation titleAddress:(NSString *)address {
    if ([[UIApplication sharedApplication] canOpenURL:
         [NSURL URLWithString:@"comgooglemaps://"]]) {
        
        NSString *urlStr = [NSString stringWithFormat: @"comgooglemaps://maps?saddr=%lf,%lf&daddr=%lf,%lf&avoid=w&zoom=14",myLocation.latitude, myLocation.longitude, toLocation.latitude, toLocation.longitude];
        if (address.length != 0) {
            urlStr = [NSString stringWithFormat: @"comgooglemaps://maps?saddr=%lf,%lf&daddr=%@&avoid=w&zoom=14",myLocation.latitude, myLocation.longitude, address];
//            urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        }
        [[self class] openURL:urlStr];
    } else {
        [[self class] openURL:[NSString stringWithFormat: @"https://www.google.com/maps?saddr=%lf,%lf&daddr=%lf,%lf&avoid=w&zoom=14",myLocation.latitude, myLocation.longitude, toLocation.latitude, toLocation.longitude]];
    }
}

+ (void)openWallet {
    [[self class] openURL:@"wallet://"];
}

+ (void)callPhone:(NSString *)phone {
    if (phone.length == 0) {
//        phone = USERManager.contactPhone;
        [BRHud showAuto:[NSString stringWithFormat:Localized(@"Error_contact"),@"number"] inView:DefaultTipsParentView];
        return;
    }
    // 清理电话号码，只保留数字和+号
    NSString *phoneStr = [phone stringByReplacingOccurrencesOfString:@" " withString:@""];
    phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
    phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@"(" withString:@""];
    phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@")" withString:@""];
    
    // 如果电话号码以0开头且没有+号，可能是越南本地号码，添加国家代码+84
    // 例如：0835001799 -> +84835001799
    if ([phoneStr hasPrefix:@"0"] && ![phoneStr hasPrefix:@"+"]) {
        phoneStr = [NSString stringWithFormat:@"+84%@", [phoneStr substringFromIndex:1]];
    }
    
    // 使用 telprompt:// 会显示确认对话框，用户体验更好
    // 如果 telprompt:// 失败，回退到 tel://
    NSString *telpromptURL = [NSString stringWithFormat:@"telprompt://%@", phoneStr];
    NSURL *telpromptURL_obj = [NSURL URLWithString:telpromptURL];
    
    if (telpromptURL_obj) {
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:telpromptURL_obj options:@{} completionHandler:^(BOOL success) {
                if (!success) {
                    // 如果 telprompt:// 失败，尝试使用 tel://
                    NSString *telURL = [NSString stringWithFormat:@"tel://%@", phoneStr];
                    NSURL *telURL_obj = [NSURL URLWithString:telURL];
                    if (telURL_obj) {
                        [[UIApplication sharedApplication] openURL:telURL_obj options:@{} completionHandler:nil];
                    }
                }
            }];
        } else {
            // iOS 10 以下使用旧方法
            BOOL opened = [[UIApplication sharedApplication] openURL:telpromptURL_obj];
            if (!opened) {
                // 如果 telprompt:// 失败，尝试使用 tel://
                NSString *telURL = [NSString stringWithFormat:@"tel://%@", phoneStr];
                NSURL *telURL_obj = [NSURL URLWithString:telURL];
                if (telURL_obj) {
                    [[UIApplication sharedApplication] openURL:telURL_obj];
                }
            }
        }
    } else {
        // URL 创建失败，尝试使用 tel://
        NSString *telURL = [NSString stringWithFormat:@"tel://%@", phoneStr];
        [[self class] openURL:telURL];
    }
}

+ (void)callPhone {
    if (USERManager.contactPhone.length == 0) return;
    [[self class] callPhone:USERManager.contactPhone];
}

+ (void)callEMail {
    // 联系客服弹窗的email硬编码为 youdianstar@gmail.com
    [[self class] callEMail:@"youdianstar@gmail.com"];
    
}

+ (void)callWhatsapp {
    if (USERManager.whatsapp.length == 0) return;
    [[self class] callWhatsapp:USERManager.whatsapp];
}

+ (void)callWhatsapp:(NSString *)phone {
    if (phone.length == 0) {
//        phone = USERManager.contactPhone;
        [BRHud showAuto:[NSString stringWithFormat:Localized(@"Error_contact"),@"number"] inView:DefaultTipsParentView];
        return;
    }
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = phone;
//        NSURL *whatsappURL = [NSURL URLWithString:@"whatsapp://app"];
    NSURL *whatsappURL = [NSURL URLWithString:[NSString stringWithFormat:@"whatsapp://send?phone=%@",phone]];
    if ([[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"whatsapp://app"]]) {
        [[UIApplication sharedApplication] openURL:whatsappURL options:@{} completionHandler:nil];
    }else {
//        DEBUGLog(@"请安装wahtsAPP");
//        [HUD showHUDWithText:@""];
    }
}

+ (void)callEMail:(NSString *)emailStr {
    if (![BRTools checkEmail:emailStr]) {
//        emailStr = USERManager.contactEmail;
        [BRHud showAuto:[NSString stringWithFormat:Localized(@"Error_contact"),@"email"] inView:DefaultTipsParentView];
        return;
    }
    
    NSString *msg = [NSString stringWithFormat:Localized(@"Dialog_SelectEmail_Message"),emailStr];
    BRCustiomAlertView *alertV = [[BRCustiomAlertView alloc] initWithTitle:Localized(@"public_notice") subTitle:msg cancelStr:Localized(@"public_cancel") succStr:Localized(@"profile_confirm") cancelAction:^{
        
    } successAction:^{
        NSMutableString *mailUrl = [[NSMutableString alloc]init];
        //添加收件人
        NSArray *toRecipients = [NSArray arrayWithObjects:emailStr, nil];
        [mailUrl appendFormat:@"mailto:%@", [toRecipients componentsJoinedByString:@","]];
        
        NSString *email = [mailUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        [[self class] openURL:email];
    } showBC:YES];
    
    [[UIApplication sharedApplication].keyWindow addSubview:alertV];
}

+ (void)openURL:(NSString *)urlStr {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr] options:@{} completionHandler:nil];
}


//获取其中某个参数
+ (NSString *)br_getParamByName:(NSString *)name URLString:(NSString *)url {
    if (url.length == 0) return @"";
    NSError *error;
    NSString *regTags=[[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)", name];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    
    // 执行匹配的过程
    NSArray *matches = [regex matchesInString:url
                                      options:0
                                        range:NSMakeRange(0, [url length])];
    for (NSTextCheckingResult *match in matches) {
        NSString *tagValue = [url substringWithRange:[match rangeAtIndex:2]];  // 分组2所对应的串
        return tagValue;
    }
    return @"";
}

+ (void)br_saveInviteCode:(NSString *)code {
    [[self class] br_saveInviteCode:code isUse:NO];
}

+ (void)br_saveInviteCode:(NSString *)code isUse:(BOOL)isUse {
    BRInviteModel *model = [BRInviteModel new];
    model.inviteCode = code;
    model.isUse = isUse;
    [[BRCacheManager share] save:model tableName:kInviteKey];
}

+ (BRInviteModel *)br_inviteCode {
    
    if ([[BRCacheManager share] hasValueForKey:kInviteKey]) {
        return (BRInviteModel *)[[BRCacheManager share] getValue:kInviteKey];
    }
    
    return [BRInviteModel new];
}

+ (void)br_removeInviteCode {
    if ([[BRCacheManager share] hasValueForKey:kInviteKey]) {
       [[BRCacheManager share] removeObj:kInviteKey];
    }
}

+ (void)br_pasteInviteCode {
    
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    NSString *str = pasteboard.string;
    
    NSLog(@"%@",str);
    if ([BRTools checkIsInviteCode:str]) {
        
        if ([str isEqualToString:BRUserManager.share.userModel.inviteCode]) {
            return;
        }
        
        [[self class] br_saveInviteCode:str];
    }
}

@end

@implementation BRInviteModel



@end
